var waitingFor; //white or black
var player = "white";
var lastSelection;
var columns = new Array();
columns[0]="a";
columns[1]="b";
columns[2]="c";
columns[3]="d";
columns[4]="e";
columns[5]="f";
columns[6]="g";
columns[7]="h";

function selectChessPiece(tableCell) {
	if (waitingFor != player) {
		return;
	}
	console.debug(tableCell);
	var tmp = $(tableCell);
	
	if (tableCell.innerHTML == "" ) {
		if (lastSelection == null) {
			return;
		}
		move(lastSelection,tableCell);
		lastSelection = null;
		return;
	}
	
	if (!tmp.hasClass(player)) {
		if (lastSelection == null) {
			console.debug("wrong piece - waiting for " + waitingFor);
			return;
		}
		console.debug("attacking with " + waitingFor + " " + lastSelection.innerHTML);
		$(lastSelection).removeClass("selected");
		move(lastSelection, tableCell);
		lastSelection=null;
		return;
	}
	
	if (tableCell == lastSelection) {
		console.debug("deselecting");
		$(lastSelection).removeClass("selected");
		lastSelection = null;
		return;
	}
	if (tmp.hasClass(player) && lastSelection != null) {
		$(lastSelection).removeClass("selected");
		tmp.addClass("selected");
		lastSelection = tableCell;
		return;
	}
	
	console.debug("selecting");
	tmp.addClass("selected");
	lastSelection=tableCell;
}

function move(from, to) {
	var from = $(from);
	var to = $(to);
	from.removeClass("selected");
	lastSelection=null;
	var move = cellToString(from)+"-"+cellToString(to);
	moveRequest(move);
}
function cellToString(cell) {
	var rowNum = 8 - cell.parent().index() ;
	return columns[cell.index()] + rowNum;
}
function setWaitingFor(color) {
	waitingFor=color;
	if (color=="white") {
		$('span#white').show();
		$('span#black').hide();
	}else {
		$('span#white').hide();
		$('span#black').show();		
	}
}